#include "socket.hh"
#include "tcp_sponge_socket.hh"
#include "util.hh"

#include <cstdlib>
#include <iostream>
#include <unistd.h>

using namespace std;

void get_URL(const string &host, const string &path) {
    // Setup Address and http header
    Address foo(host, "http");
    // cout << "IP address:" <<  foo.to_string() << endl;
    /*
        GET /hello HTTP/1.1\r\n
        Host: cs144.keithw.org\r\n
        Connection: close\r\n
        \r\n
    */
    string sendcontent;

    sendcontent = "GET " + path + " HTTP/1.1\r\n";
    sendcontent += "Host: cs144.keithw.org\r\n";
    sendcontent += "Connection: close\r\n";
    sendcontent += "\r\n";

    // cout << "Header :" + sendcontent << endl;

    // setup socket

    FullStackSocket socket = FullStackSocket();
    socket.connect(foo);

    socket.write(sendcontent);

    sleep(5);

    auto recv_content = socket.read();

    sleep(1);
    socket.wait_until_closed();
    // socket.shutdown(SHUT_RDWR);
    cout << recv_content;
    // cerr << "Function called: get_URL(" << host << ", " << path << ").\n";
}

int main(int argc, char *argv[]) {
    try {
        if (argc <= 0) {
            abort();  // For sticklers: don't try to access argv[0] if argc <=
                      // 0.
        }

        // The program takes two command-line arguments: the hostname and "path"
        // part of the URL. Print the usage message unless there are these two
        // arguments (plus the program name itself, so arg count = 3 in total).
        if (argc != 3) {
            cerr << "Usage: " << argv[0] << " HOST PATH\n";
            cerr << "\tExample: " << argv[0] << " stanford.edu /class/cs144\n";
            return EXIT_FAILURE;
        }

        // Get the command-line arguments.
        const string host = argv[1];
        const string path = argv[2];

        // Call the student-written function.
        get_URL(host, path);
    } catch (const exception &e) {
        cerr << e.what() << "\n";
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
